package com.hspedu.newData.dmsxl.树.二叉树路径.路径;

import com.hspedu.leetcode.Test;
import com.hspedu.newData.dmsxl.ds.TreeNode;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @Author: yh
 * @description: 
 * @CreateTime: 2025-04-23 
 * @Version: 1.0
 */

public class LC440左叶子之和 {


    // 迭代法
    public int sumOfLeftLeaves(TreeNode root) {
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        int sum = 0;
        while(!queue.isEmpty()){
            int len = queue.size();
            while(len > 0){
                TreeNode node = queue.poll();

                if (node.left != null && node.left.left == null && node.left.right == null){
                    sum += node.left.val;
                }

                if (node.left != null) queue.offer(node.left);
                if (node.right != null) queue.offer(node.right);

                len --;
            }
        }
        return sum;
    }

    // 递归法
    public int sumOfLeftLeaves1(TreeNode root) {
        if (root == null){
            return 0;
        }

        int leftValue = sumOfLeftLeaves1(root.left);
        int rightValue = sumOfLeftLeaves1(root.right);
        int val = 0;
        if (root.left != null && root.left.left == null && root.left.right == null){
            val = root.left.val;
        }
        return val + leftValue + rightValue;
    }

}
